(function ($) {
    var dataTable, searchBtn, addBtn,
        addOrEditModal, addOrEditModalOkBtn, addOrEditModalForm, addOrEditModalFormValid,
        id, shortLinkCode, srcLink;
    pageObj = {};
    pageObj.init = function () {
        id = $('#addOrEditModal [name="id"]');
        shortLinkCode = $('#addOrEditModal [name="shortLinkCode"]');
        srcLink = $('#addOrEditModal [name="srcLink"]');


        searchBtn = $('#searchBtn');

        addBtn = $('#addBtn');
        addOrEditModal = $('#addOrEditModal');
        addOrEditModalOkBtn = $('#addOrEditModal  .ok');


        addOrEditModalForm = $('#addOrEditModalForm');

        dataTable = $("#dataTable").dataTable({
            "destroy": true,    //初始化表格
            "searching": false,//搜索框
            "deferRender": true,
            "processing": true,
            "serverSide": true,
            "aLengthMenu": [10, 20, 30, 50, 100, 500],  //更改显示记录数选项
            "ajax": {
                // url可以直接指定远程的json文件，或是MVC的请求地址 /Controller/Action
                url: base_url + "/sl/pageList",
                type: 'POST',
                contentType: "application/json",
                dataSrc: function (json) {

                    json.draw = json.data.draw;
                    //所有的总件数
                    json.recordsTotal = json.data.total;
                    // 筛选后的总件数
                    json.recordsFiltered = json.data.total;

                    return json.data.list || [];
                },
                // 传给服务器的数据，可以添加我们自己的查询参数
                data: function (param) {
                    var obj = {};
                    obj.shortLinkCode = $("#shortLinkCode").val();
                    obj.srcLink = $("#srcLink").val();


                    obj.start = param.start || 1;
                    obj.length = param.length;
                    return JSON.stringify(obj);
                }
            },
            "language": {
                "sProcessing": "处理中...",
                "sLengthMenu": "每页 _MENU_ 条记录",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "第 _PAGE_ 页 ( 总共 _PAGES_ 页，_TOTAL_ 条记录 )",
                "sInfoEmpty": "无记录",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "搜索",
                "sUrl": "",
                "sEmptyTable": "暂无数据",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上一页",
                    "sNext": "下一页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            },
            "columns": [
                {
                    "data": 'id',
                    "bSortable": false,
                    "visible": false
                },
                {
                    "title": '短链接编码',
                    "data": 'shortLinkCode',
                    "bSortable": false,
                    "visible": true,
                    "width": '20%'
                },
                {
                    "title": '短链接',
                    "data": 'shortLink',
                    "bSortable": false,
                    "visible": true,
                    "width": '20%',
                    "render": function (data, type, row, meta) {
                        return  taotaoLink.formatStr('<a href="{{link}}" target="_blank">{{link}}</a>',{link:row.shortLink});
                    }
                },
                {
                    "title": '长链接',
                    "data": 'srcLink',
                    "bSortable": false,
                    "visible": true,
                    "width": '30%',
                    "render": function (data, type, row, meta) {
                        return  taotaoLink.formatStr('<a href="{{link}}" target="_blank">{{link}}</a>',{link:row.srcLink});
                    }
                },
                {
                    "title": '操作',
                    "data": null,
                    "bSortable": false,
                    "visible": true,
                    "width": '10%',
                    "render": function (data, type, row, meta) {

                        var html = '<p>';

                        html += '<button class="btn btn-warning btn-xs del" type="button">删除</button>';
                        html += '</p>';
                        return html;
                    }
                }
            ]

        });


        addOrEditModalFormValid = addOrEditModalForm.validate({
            onsubmit: true,
            errorElement: 'span',
            errorClass: 'has-error',
            focusInvalid: true,
            rules: {
                srcLink: {
                    required: true
                }
            },
            messages: {
                srcLink: {
                    required: "请输入长链接"
                }
            },
            highlight: function (element) {
                // $(element).closest('.form-group').addClass('has-error');
                var $element = $(element);
                $element.closest('.form-group').addClass( "has-error" ).removeClass( "has-success" );
            },
            success: function (label) {
                // alert("success");
                label.closest('.form-group').removeClass('has-error');
                label.remove();
            },
            //resetForm函数触发
            unhighlight: function (element, errorClass, validClass) {
                var $element = $( element );
                $element.closest('.form-group').removeClass("has-error");

            },
            errorPlacement: function (error, element) {
                element.parent('div').append(error);
            }
        });

    };

    pageObj.clearAddOrEditModalForm = function () {
        addOrEditModalFormValid.resetForm();
        addOrEditModalForm.find(".form-group").removeClass("has-error");
        addOrEditModalForm.find('input,textarea,select').val('');
    }


    pageObj.bindEvent = function () {
        searchBtn.on('click', function () {
            dataTable.fnDraw();
        });

        //新增
        addBtn.on('click', function () {
            pageObj.clearAddOrEditModalForm();

            $('#addOrEditModal .modal-title').html("新增");
            addOrEditModal.modal('show');
        });

        //保存
        addOrEditModalOkBtn.on('click', function () {
            addOrEditModalFormValid.form();
            // alert(addOrEditModalFormValid.valid());
            if (!addOrEditModalFormValid.valid()) {
                return;
            }

            taotaoLink.post("/sl/add", {
                "id": id.val(),
                "srcLink": srcLink.val()
            }, {
                succCallback: function (data, status) {
                    addOrEditModal.modal('hide');
                    dataTable.fnDraw('page');
                }
            });


            return false;
        });

        //启用禁用
        dataTable.on('click', '.btn.del', function () {
            var tr = $(this).closest("tr")[0];
            var data = dataTable.fnGetData(tr);

            taotaoLink.post("/sl/del", [data.id], {
                succCallback: function (data, status) {
                    dataTable.fnDraw('page');
                }
            });

            return false;
        });

    };

    pageObj.start = function () {
        pageObj.init();
        pageObj.bindEvent();
    }


    window.userList = pageObj;


    $(function () {
        pageObj.start();
    });
})(jQuery);